<!--  -->
<template>
  <div class="app-container">

    <!-- header -->
    <el-card>
      <div slot="header" class="header">
        <span>活动管理</span>
        <el-button type="success" icon="el-icon-plus" size="small" @click="onClickActivity('add')">添加活动</el-button>
      </div>

      <div style="marginTop:20px" class="filter-container">
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item label="活动名称">
            <el-input v-model="searchData.name" clearable></el-input>
          </el-form-item>
          <el-form-item label="活动状态">
            <el-select v-model="searchData.status" placeholder="请选择" clearable>
              <el-option v-for="item in searchData.options" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="onClickActivity('search')">查询</el-button>
        </el-form>
      </div>
    </el-card>

    <!-- body -->
    <el-card style="marginTop:20px">
      <el-table :data="tableData" style="width: 100%">
        <el-table-column type="index" label="#" min-width="80" />
        <el-table-column prop="name" label="活动名称" min-width="150" />
        <el-table-column prop="subName" label="活动子名称" min-width="150" show-overflow-tooltip />
        <el-table-column prop="type" label="活动类型" min-width="150">
          <template slot-scope="scope">
            {{scope.row.type | activityTypeFilter}}
          </template>
        </el-table-column>
        <el-table-column prop="date" label="活动时间" min-width="310">
          <template slot-scope="scope">
            {{scope.row.startTime}} 至 {{scope.row.endTime}}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status | activityTagFilter" effect="light" size="small">{{scope.row.status| activityStatusFilter}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center">
          <template slot-scope="scope">
            <el-button v-if="status.canStart.includes(scope.row.status)" @click="onClickActivity('start',scope.row)" type="text">启动</el-button>
            <el-button v-if="status.canStop.includes(scope.row.status)" @click="onClickActivity('stop',scope.row)" type="text">暂停</el-button>
            <el-button v-if="status.canEdit.includes(scope.row.status)" @click="onClickActivity('edit',scope.row)" type="text">编辑</el-button>
            <el-button v-if="status.canDelete.includes(scope.row.status)" @click="onClickActivity('delete',scope.row)" type="text" class="red">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination background layout="prev, pager, next" @current-change="currentChange" :page-count="Math.ceil(this.pageInfo.total / this.pageInfo.pageSize)"></el-pagination>
      </div>
    </el-card>

    <!-- dialog -->
    <el-dialog :visible.sync="dialogFormVisible" :destroy-on-close="true" width="80%" :title=" editData.isEdit?'编辑活动':'添加活动'" :before-close="onBeforeClose">
      <el-form ref="editForm" :rules="editRules" :model="editData">
        <el-form-item label="活动名称" :label-width="formLabelWidth" prop="name" required>
          <el-input v-model="editData.name" placeholder="请输入活动名称" clearable />
        </el-form-item>
        <el-form-item label="活动子名称" :label-width="formLabelWidth" prop="subName">
          <el-input v-model="editData.subName" placeholder="请输入活动子名称" clearable />
        </el-form-item>
        <el-form-item label="活动时间" :label-width="formLabelWidth" prop="activityDate" required>
          <el-date-picker v-model="editData.activityDate" :picker-options="pickerOption" @change="onChangePickerDate" type="datetimerange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" clearable />
        </el-form-item>
        <el-form-item label="活动类型" :label-width="formLabelWidth" prop="type" required>
          <el-radio-group v-model="editData.type" @change="onChangeType">
            <el-radio v-for="item in editData.typeOptions" :key="item.value" :label="item.value">{{item.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="活动状态" :label-width="formLabelWidth" prop="status" v-if="editData.isEdit">
          <el-tag :type="editData.status | activityTagFilter" effect="dark">{{editData.status | activityStatusFilter}}</el-tag>
        </el-form-item>
        <el-form-item label="活动banner" :label-width="formLabelWidth" prop="banners" required>
          <upload-image :defaultList='editData.bannerList' color="#1890ff" class="editor-upload-btn" :limit="6" @successCBK="syncImageList($event)" />
        </el-form-item>
        <el-form-item label="商品列表" :label-width="formLabelWidth" prop="activityDetailDTOs">
          <template>
            <div class="tb">
              <div class="tb-tr">
                <el-cascader class="tb-td-v" placeholder="请选择商品分类" v-model="editData.categoryCode" :options="editData.categoryList" @change="onChangeCategory" clearable :props="{label: 'categoryName',value: 'categoryCode'}"></el-cascader>
                <el-select class="tb-td-v" placeholder="请输入商品名称" v-model="editData.selectedOption" :remote-method="getProductItem" ref="productNameInput" :loading="editData.isLoading" filterable remote reserve-keyword collapse-tags>
                  <el-option v-for="item in editData.options" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
                <el-button type="primary" @click="onClickAddProduct">添加</el-button>
              </div>
              <div class="tb-tr">
                <el-table :border="true" :data="editData.activityDetailDTOs" style="width:100%">
                  <el-table-column label="#" type="index" />
                  <el-table-column label="商品名称" prop="productName" />
                  <el-table-column label="实际价格" prop="realPrice" align="center" />
                  <el-table-column label="活动价格" prop="activityPrice" align="center">
                    <template slot-scope="scope">
                      <el-input-number style="width:100%" v-model="scope.row.activityPrice" controls-position="right" :min="0.01" :precision="2" :step="0.1"></el-input-number>
                    </template>
                  </el-table-column>
                  <el-table-column label="实际库存" prop="realNum" align="center" />
                  <el-table-column label="活动库存" prop="activityNum" align="center">
                    <template slot-scope="scope">
                      <el-input-number style="width:100%" v-model="scope.row.activityNum" controls-position="right" :min="0" :max="scope.row.realNum" :step="1"></el-input-number>
                    </template>
                  </el-table-column>
                  <el-table-column label="每人限量" prop="limitNum" align="center">
                    <template slot-scope="scope">
                      <el-input-number style="width:100%" v-model="scope.row.limitNum" controls-position="right" :min="0" :max="scope.row.activityNum" :step="1"></el-input-number>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="120" align="center">
                    <template slot-scope="scope">
                      <i class="el-icon-delete tb-td-icon" @click="onClickProduct('delete',scope.row)"></i>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </template>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="onClickCancel">取 消</el-button>
        <el-button type="success" @click="onClickSave">提 交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import dayjs from 'dayjs';
import config from './config';

export default {
  name: '',
  components: {},
  props: {},
  data() {
    return {
      dialogFormVisible: false,
      formLabelWidth: '100px',
      pageInfo: {
        pageNum: 1, // 当前页码
        pageSize: 10, // 展示数量
        total: 1, // 总记录数
      },
      searchData: {
        name: '',
        status: '',
        options: this.getActivityStatus(),
      },
      tableData: [],

      editData: {
        isEdit: false,
        activityDate: [],
        isLoading: false,
        options: [],
        categoryCode: '',
        categoryList: [],
        selectedOption: null,
        activityDetailDTOs: [],
        banners: [],
        bannerList: [],
        type: 1,
        typeOptions: this.getActivityType(),
      },
      editRules: {
        name: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
        activityDate: [
          { required: true, message: '请选择活动时间', trigger: 'blur' },
        ],
        type: [{ required: true, message: '请选择活动类型', trigger: 'blur' }],
        banners: [
          { required: true, message: '请上传活动banner', trigger: 'blur' },
        ],
      },

      pickerOption: {
        disabledDate: (time) => {
          return time.getTime() + 24 * 3600 * 1000 < Date.now();
        },
      },
      dateFormat: 'YYYY-MM-DD HH:mm:ss',

      status: {
        canEdit: ['0', '1', '2'], // 可编辑 暂停状态暂时不支持编辑！
        canStart: ['2'], // 启动
        canStop: ['1'], // 暂停
        canDelete: ['0'], // 删除
      },
    };
  },
  created() {},
  mounted() {
    this.getActivityList();
  },
  computed: {},
  filters: {
    activityStatusFilter(status) {
      return config.status[status];
    },
    activityTagFilter(status) {
      return config.statusTag[status];
    },
    activityTypeFilter(type) {
      return config.type[type];
    },
  },
  methods: {
    /** 配置、状态、上传图片等相关 */
    getActivityStatus() {
      return Object.getOwnPropertyNames(config.status).map((value) => {
        return { label: config.status[value], value: value };
      });
    },

    onChangePickerDate() {
      const startAt = (new Date(this.editData.activityDate[0]) * 1000) / 1000;
      if (startAt < Date.now()) {
        this.editData.activityDate[0] = new Date();
      }
    },

    currentChange(val) {
      this.pageInfo.pageNum = val;
      this.getActivityList();
    },

    syncImageList(list) {
      this.editData.banners = list.map((e) => {
        return e.url;
      });
    },

    getActivityType() {
      return Object.getOwnPropertyNames(config.type).map((value) => {
        console.log('value', value, 'config.type[value]', config.type[value]);
        return { label: config.type[value], value: +value };
      });
    },

    /** 窗体相关 */
    onBeforeClose(done) {
      this.editData = {
        isEdit: false,
        name: '',
        activityDate: [],
        categoryCode: [],
      };
      done();
    },

    onClickCancel() {
      this.dialogFormVisible = false;
      this.$refs['editForm'].resetFields();
    },

    onClickSave() {
      this.$refs['editForm'].validate((valid) => {
        if (!valid) return;
        if (this.editData.activityDetailDTOs.length < 1) {
          this.$message.warning('请添加商品');
          return;
        }
        if (this.editData.isEdit) {
          this.modifyActivity();
        } else {
          this.addActivity();
        }
      });
    },

    /** 活动相关 */
    onClickActivity(action, row) {
      switch (action) {
        case 'add':
          this.onClickAdd();
          break;
        case 'search':
          this.onClickSearch(row);
          break;
        case 'edit':
          this.onClickEdit(row);
          break;
        case 'start':
          this.onClickStart(row);
          break;
        case 'stop':
          this.onClickStop(row);
          break;
        case 'delete':
          this.onClickDelete(row);
          break;

        default:
          break;
      }
    },

    onClickSearch() {
      this.pageInfo.pageNum = 1;
      this.getActivityList();
    },

    onClickAdd() {
      this.editData = {
        ...{},
        ...this.editData,
        ...{ isEdit: false },
      };
      this.dialogFormVisible = true;
      this.getCategoryList();
    },

    onClickEdit(row) {
      this.editData = {
        ...{},
        ...this.editData,
        ...{ isEdit: true },
      };
      this.dialogFormVisible = true;
      this.getActivityInfo(row);
      this.getCategoryList();
    },

    onChangeType(value) {
      console.log('value', value);
      this.editData.type = value;
    },

    async onClickStart(row) {
      if (this.status.canStart.includes(row.status)) {
        const confirm = await this.$confirm(
          `此操作将【启动】该活动, 是否继续?`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        ).catch(() => {});

        confirm && this.stopOrStartActivity(row);
      }
    },

    async onClickStop(row) {
      if (this.status.canStop.includes(row.status)) {
        const confirm = await this.$confirm(
          `此操作将【暂停】该活动, 是否继续?`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        ).catch(() => {});

        confirm && this.stopOrStartActivity(row);
      }
    },

    async onClickDelete(row) {
      const confirm = await this.$confirm(
        `此操作将【永久删除】该活动, 是否继续?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch(() => {});

      confirm && this.deleteActivity(row);
    },

    async getActivityList() {
      const params = {
        name: this.searchData.name,
        status: this.searchData.status,
        pageNum: this.pageInfo.pageNum,
        pageSize: this.pageInfo.pageSize,
        needTotalCount: true,
      };
      const response = await this.$api.getActivityList(params);
      this.tableData = response.data;
      this.pageInfo.total = response.total;
    },

    async addActivity() {
      const { name, subName, type, activityDate, activityDetailDTOs, banners } =
        this.editData;
      const { success } = await this.$api.addActivity({
        name,
        subName,
        type,
        activityDetailDTOs,
        banners,
        startTime: dayjs(activityDate[0]).format(this.dateFormat),
        endTime: dayjs(activityDate[1]).format(this.dateFormat),
      });
      if (success) {
        this.$message.success('添加成功');
        this.dialogFormVisible = false;
        this.resetProductOption();
        this.getActivityList();
      }
    },

    async modifyActivity() {
      const {
        id,
        name,
        subName,
        type,
        activityDate,
        activityDetailDTOs,
        banners,
      } = this.editData;
      const { success } = await this.$api.modifyActivity({
        id,
        name,
        subName,
        type,
        activityDetailDTOs,
        banners,
        startTime: dayjs(activityDate[0]).format(this.dateFormat),
        endTime: dayjs(activityDate[1]).format(this.dateFormat),
      });
      if (success) {
        this.$message.success('修改成功');
        this.dialogFormVisible = false;
        this.resetProductOption();
        this.getActivityList();
      }
    },

    async deleteActivity({ id }) {
      const response = await this.$api.deleteActivity({ id });
      if (response.success) {
        this.$message.success('删除成功');
        this.getActivityList();
      }
    },

    async stopOrStartActivity({ id }) {
      const { success } = await this.$api.stopOrStartActivity({ id });
      if (success) {
        this.$message.success('设置成功');
        this.getActivityList();
      }
    },

    /** 活动商品相关 */
    onChangeCategory(row) {
      if (this.editData.categoryCode.length > 1) {
        this.editData.categoryCode =
          this.editData.categoryCode[this.editData.categoryCode.length - 1];
      }
      this.resetProductOption();
      this.getProductItem();

      // 分类不为空，商品名称获取焦点
      if (this.editData.categoryCode.length > 1) {
        this.$refs.productNameInput.focus();
      }
    },

    onClickProduct(action, row) {
      switch (action) {
        case 'add':
          this.onClickAddProduct();
          break;
        case 'delete':
          this.onClickDeleteProduct(row);
          break;
        default:
          break;
      }
    },

    onClickAddProduct() {
      if (this.editData.selectedOption === null) {
        this.$message.warning(`请输入商品名称，进行搜索并添加`);
        return;
      }

      const option = this.editData.options.find(
        (e) => e.value === this.editData.selectedOption
      );
      const exist = this.editData.activityDetailDTOs.some(
        (e) => e.productItemId === option.value
      );

      if (exist) {
        this.$message.warning(`商品【${option.label}】，已存在列表中！`);
        return;
      }

      this.editData.activityDetailDTOs.push({
        productId: option.key,
        productItemId: option.value,
        productName: option.label,
        realNum: option.num,
        realPrice: option.price,
        activityNum: 0,
        activityPrice: 0,
        limitNum: 0,
      });
    },

    resetProductOption() {
      this.editData = {
        ...this.editData,
        ...{ options: [] },
        ...{ selectedOption: null },
      };
    },

    async onClickDeleteProduct(row) {
      const confirm = await this.$confirm(
        `确定将【${row.productName}】从该活动中删除, 是否继续?`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch(() => {});

      confirm && this.deleteActivityProduct(row);
    },

    async getActivityInfo({ id }) {
      const params = {
        activityId: id,
      };
      const { data } = await this.$api.getActivityInfo(params);
      this.editData = {
        ...this.editData,
        ...data,
        ...{
          bannerList: data.banners.map((e) => {
            return { url: e };
          }),
        },
        ...{ activityDate: [data.startTime, data.endTime] },
      };
    },

    async deleteActivityProduct(row) {
      const currentIndex = this.editData.activityDetailDTOs.findIndex(
        (e) => e.productItemId === row.productItemId
      );
      this.editData.activityDetailDTOs.splice(currentIndex, 1);

      if (this.editData.isEdit) {
        const response = await this.$api.deleteActivityProduct({ id: row.id });
        if (response.success) {
          this.$message.success('删除成功');
        }
      }
    },

    async getProductItem(keyword) {
      const { categoryCode } = this.editData;
      if (keyword === '' && categoryCode === '') {
        this.editData.options = [];
        return;
      }

      const params = { keyword, categoryCode };
      if (keyword === undefined) delete params.keyword;

      this.editData.isLoading = true;
      const { success, data, errMessage } = await this.$api.getProductItem(
        params
      );
      if (!success) {
        this.$message({
          type: 'warning',
          message: `${errMessage || '系统繁忙，请稍后再试'}`,
        });
        this.editData.isLoading = false;
        return;
      }

      this.editData.options = data.map((item) => {
        return {
          label: item.title,
          value: item.id,
          key: item.productId,
          price: item.price,
          num: item.num,
        };
      });

      this.editData.isLoading = false;
    },

    async getCategoryList() {
      const response = await this.$api.getCategoryList();
      const { data } = response;
      this.editData.categoryList = data;
    },
  },
};
</script>

<style lang='scss' scoped>
.app-container {
  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
.tb {
  display: flex;
  flex-direction: column;
}
.tb-tr {
  display: flex;
  flex-direction: row;
  margin-bottom: 10px;
}
.tb-td-t {
  flex-shrink: 0;
  margin-right: 20px;
}
.tb-td-v {
  width: 50%;
  margin-right: 20px;
  flex-grow: 1;
}
.tb-td-icon {
  font-size: 18px;
  color: red;
  cursor: pointer;
}
.tb-td-icon:hover {
  color: #409eff;
}
::v-deep {
  .el-dialog__body {
    padding-bottom: 0;
  }
  .el-dialog__footer {
    padding: 10px 20px;
  }
}
</style>
